/**
 * 图片文件左侧文件函数
 * @param type
 */
import {CheckboxValueType, ElMessage, ElTree} from "element-plus";
import feedback from "@/utils/feedback";
import {ShallowRef, UnwrapNestedRefs} from "@vue/reactivity";
import {Ref} from "vue";
import {usePagerManager} from "@/manager/base/PagerManager";
import {
    fileCateAdd,
    fileCateDelete,
    fileCateEdit,
    fileCateLists,
    fileDelete, fileList,
    fileMove, fileRename
} from "@/api/albums/AlbumsGroupController";


/**
 * 处理文件的钩子函数
 *
 * @param groupId 选中的分组id
 * @param type 文件类型   10 - 20
 * @param limit 页码
 * @param size 页数量
 */
export function useFIleManager(groupId: Ref<string | number>, type: Ref<number>, limit: Ref<number>, size: number) {

    // 选中数据
    const select: Ref<any[]> = ref([])


    const fileParams: UnwrapNestedRefs<any> = reactive({
        name: '',
        type: type,
        cid: groupId
    })

    // 获取分页数据
    const {pagerData, getPageLists, resetParams, resetOnePage} = usePagerManager({
        fetchFun: fileList,
        params: fileParams,
        firstLoading: false,
        size
    })


    /**
     * 获取文件列表
     */
    function getFileList() {
        getPageLists()
    }

    /**
     * 重置文件为第一页
     */
    function refresh() {
        resetOnePage()
    }


    /**
     * 是否选中
     *
     * @param id
     */
    function isSelect(id: number): boolean {

        if (!!select) {
            select.value.find((item: any) => item.id == id)
        }
        return false
    }


    /**
     * 清空选择器
     *
     */
    function clearSelect() {
        select.value = []
    }


    /**
     * 取消选择
     *
     * @param id
     */
    function cancelSelect(id: number) {
        if (!!select) {
            select.value.filter((item: any) => item.id != id)
        }
    }


    /**
     * 更改文件名
     *
     * @param value
     * @param id
     */
    async function handleFileRename(value: string, id: number) {
        await fileRename({
            id,
            name: value
        })
        getFileList()
    }

    /**
     * 批量删除
     * @param id
     */
    async function batchFileDelete(id?: number[]) {

        await feedback.confirm(
            '确认删除后，本地或云存储文件也将同步删除，如文件已被使用，请谨慎操作！'
        )

        let ids

        if (!!id) {
            ids = id
        } else {
            ids = select.value.map((item: any) => item.id);

        }

        await fileDelete({ids})
        getFileList()
        clearSelect()


    }


    /**
     * 全选
     *
     * @param value
     */
    const tableRef: ShallowRef = shallowRef()
    const isIndeterminate: Ref<boolean> = ref(false)

    function selectAll(value: CheckboxValueType) {
        isIndeterminate.value = false
        tableRef.value?.toggleAllSelection()
        if (value) {
            select.value = [...pagerData.lists]
        } else {
            clearSelect()
        }
    }


    /**
     * 选择文件
     * @param item
     */
    function selectFile(item: any) {
        const index = select.value.findIndex((items: any) => items.id == item.id)
        if (index != -1) {
            select.value.splice(index, 1)
            return
        }
        if (select.value.length == limit.value) {
            if (limit.value == 1) {
                select.value = []
                select.value.push(item)
                return
            }
            ElMessage.warning('已达到选择上限')
            return
        }
        select.value.push(item)
    }




    /**
     * 批量文件移动
     */
    const moveId: Ref<number> = ref(0)

    const batchFileMove = async () => {
        const ids = select.value.map((item: any) => item.id)

        await fileMove({ids, cid: moveId.value})
        moveId.value = 0
        getFileList()
        clearSelect()
    }

    const isCheckAll: Ref<boolean> = ref(false)
    const listShowType: Ref<string>= ref('normal')
    return {
        isCheckAll,
        listShowType,

        tableRef,
        moveId,
        pagerData,
        fileParams,
        select,
        isIndeterminate,
        getFileList,
        refresh,
        batchFileDelete,
        batchFileMove,
        selectFile,
        isSelect,
        clearSelect,
        cancelSelect,
        selectAll,
        handleFileRename
    }
}


/**
 *
 * 使用右侧文件管理器
 *
 * @param type
 */

export function useLeftFileManager(type: number) {
    const treeRef: ShallowRef = shallowRef<InstanceType<typeof ElTree>>()

    // 分组列表
    const groupLists: Ref<any[]> = ref([])

    // 选中的分组id
    const groupId: Ref<number | string> = ref('')


    /**
     * 获取分组列表
     */
    async function getGroupLists() {
        groupLists.value = await fileCateLists({type})

        const item: any[] = [
            {
                name: '全部',
                id: ''
            },
            {
                name: '未分组',
                id: 0
            }
        ]

        groupLists.value.unshift(...item)

        setTimeout(() => {
            treeRef.value?.setCurrentKey(groupId.value)
        }, 0)
    }


    /**
     *  添加分组
     *
     * @param value
     */
    async function handleAddGroup(value: string) {
        await fileCateAdd({
            type,
            name: value,
            pid: 0
        })
        await getGroupLists()
    }


    /**
     * 编辑分组
     *
     * @param value
     * @param id
     */
    async function handleEditCate(value: string, id: number) {
        await fileCateEdit({id, name: value})
        await getGroupLists()
    }


    /**
     * 删除分组
     *
     * @param id
     */
    async function handleDeleteCate(id: number) {
        await feedback.confirm('确定要删除？')
        await fileCateDelete({id})
        groupId.value = ''
        await getGroupLists()
    }


    /**
     * 选中分类
     *
     * @param item
     */
    function handleGroupIdSelect(item: any) {
        groupId.value = item.id
    }

    return {
        treeRef,
        groupLists,
        groupId,
        getGroupLists,
        handleAddGroup,
        handleEditCate,
        handleDeleteCate,
        handleGroupIdSelect
    }


}